import { PLAY_MODE } from '@/assets/js/constant'
import { shuffle, loadFavouriteListFromLocal } from '@/assets/js/utils'

const state = {
  sequenceList: [], // 列表顺序
  playList: [], // 播放顺序
  playing: false, // 是否播放
  playMode: PLAY_MODE.SEQUENCE, // 播放模式
  currentIndex: 0, // 当前播放索引
  fullScreen: false, // 是否全屏
  favouriteList: loadFavouriteListFromLocal() || [] // 收藏列表
}

const getters = {
  currentSong(state) {
    return state.playList[state.currentIndex] || {}
  }
}

const mutations = {
  setPlayingState(state, playing) {
    state.playing = playing
  },

  setSequenceList(state, sequenceList) {
    state.sequenceList = sequenceList
  },

  setPlayList(state, playList) {
    state.playList = playList
  },

  setPlayMode(state, playMode) {
    state.playMode = playMode
  },

  setCurrentIndex(state, currentIndex) {
    state.currentIndex = currentIndex
  },

  setFullScreen(state, fullScreen) {
    state.fullScreen = fullScreen
  },

  setFavouriteList(state, list) {
    state.favouriteList = list
  },

  setSongLyric(state, { song, lyric }) {
    state.sequenceList.forEach(item => {
      if (item.id === song.id) {
        item.lyric = lyric
      }
    })
  }
}

const actions = {
  selectPlay({ commit, state }, { list, index }) {
    commit('setPlayingState', true)
    commit('setPlayMode', PLAY_MODE.SEQUENCE)
    commit('setSequenceList', list)
    commit('setPlayList', list)
    commit('setCurrentIndex', index)
    commit('setFullScreen', true)
  },

  randomPlay({ commit }, list) {
    commit('setPlayingState', true)
    commit('setPlayMode', PLAY_MODE.RANDOM)
    commit('setSequenceList', list)
    commit('setPlayList', shuffle(list))
    commit('setCurrentIndex', 0)
    commit('setFullScreen', true)
  },

  changeMode({ commit, state, getters }, mode) {
    const currentId = getters.currentSong.id
    if (mode === PLAY_MODE.RANDOM) {
      commit('setPlayList', shuffle(state.sequenceList))
    } else {
      commit('setPlayList', state.sequenceList)
    }
    const nowIndex = state.playList.findIndex(item => item.id === currentId)
    commit('setCurrentIndex', nowIndex)
    commit('setPlayMode', mode)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
